<?php

namespace app\admin\logic;

use app\common\exception\ApiException;
use app\common\model\CompanyRole;
use app\common\model\CompanyUser;
use app\common\model\CompanyUserRole;
use think\facade\Validate;

/**
 * 经销商逻辑层
 */
class CompanyUserLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new CompanyUser();
    }

    public function getList($companyId = 0) : array
    {
        if (!empty($companyId)) {
            return $this->model->where('company_id', $companyId)->with(['role' => function($query) {
                $query->visible(['id', 'company_id', 'role_name']);
            }])->hidden(['password'])->paginate(request()->input('limit', 10), false, ['page' => request()->input('page', 1)])->toArray();
        }
        return [];
    }

    public function getRoleList($companyId = 0) : array
    {
        if (!empty($companyId)) {
            return CompanyRole::where('company_id', $companyId)->field('id, role_name, role_type')->order('id asc')->select()->toArray();
        }
        return [];
    }

    public function saveCompanyUser(array $params)
    {
        $this->validateCompanyUser($params);
        $params['password'] = company_password_hash(empty($params['password']) ? config('common.default_password') : $params['password']);
        $params['create_time'] = time();
        $userRoleIds = !is_array($params['role_ids']) ? [$params['role_ids']] : $params['role_ids'];
        unset($params['role_ids']);
        return $this->model->transaction(function () use ($params, $userRoleIds) {
            $userId = $this->model->insertGetId($params);
            if ($userId > 0) {
                $povitData = array_map(function($roleId) use ($userId, $params) {
                    return [
                        'company_user_id' => $userId,
                        'company_role_id' => $roleId,
                        'company_id' => $params['company_id'],
                    ];
                }, $userRoleIds);
                CompanyUserRole::insertAll($povitData);
            }
            return $userId;
        });
    }

    public function updateCompanyUser(array $params, $id = 0)
    {
        $this->validateCompanyUser(array_merge($params, ['id' => $id]), 'edit');
        $params['update_time'] = time();
        if (empty($id)) {
            throw new ApiException('用户ID参数缺失');
        }
        $userInfo = $this->model->where('id', $id)->where('company_id', $params['company_id'])->findOrEmpty();
        if ($userInfo->isEmpty()) {
            throw new ApiException('用户不存在');
        }
        $userRoleIds = !is_array($params['role_ids']) ? [$params['role_ids']] : $params['role_ids'];
        unset($params['role_ids']);
        if (!empty($params['password'])) {
            $params['password'] = company_password_hash($params['password']);
        } else {
            unset($params['password']);
        }
        return $this->model->transaction(function () use ($params, $userRoleIds, $id) {
            $res = $this->model->update($params, ['id' => $id]);
            if ($res !== false) {
                CompanyUserRole::where('company_user_id', $id)->delete();
                $povitData = array_map(function($roleId) use ($id, $params) {
                    return [
                        'company_user_id' => $id,
                        'company_role_id' => $roleId,
                        'company_id' => $params['company_id'],
                    ];
                }, $userRoleIds);
                CompanyUserRole::insertAll($povitData);
            }
            return $res;
        });
    }

    public function deleteCompanyUser($ids)
    {
        if (empty($ids)) {
            throw new ApiException('用户ID参数缺失');
        }
        $ids = is_array($ids) ? $ids : [$ids];
        return $this->model->transaction(function () use ($ids) {
            CompanyUserRole::where('company_user_id', 'in', $ids)->delete();
            return $this->model->destroy($ids);
        });
    }


    private function validateCompanyUser(array $params, $scene = 'add')
    {
        $rule = [
            'company_id' => 'require|number',
            'role_ids' => 'require',
            'username' => 'require|chsAlphaNum',
            'password' => 'require|alphaNum',
        ];
        $message = [
            'company_id.require' => '企业ID参数缺失',
            'role_ids.require' => '请选择角色',
            'username.require' => '请输入用户名',
            'password.require' => '请输入密码',
        ];

        if ($scene == 'edit') {
            unset($rule['password']);
        }
        $validate = validate($rule, $message);
        if (!$validate->check($params)) {
            throw new ApiException($validate->getError());
        }
        $existsUsername = CompanyUser::where('company_id', $params['company_id'])->where('username', $params['username'])->findOrEmpty();
        if (!$existsUsername->isEmpty() && ($scene == 'add' || ($scene == 'edit' && $existsUsername->id != $params['id']))) {
            throw new ApiException('已存在相同的用户名');
        }
        return true;
    }    

}
